package com.uft.service;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.uft.utils.UftUtils;

@Service
public class TaskTracker {
	private  static Logger  logger = Logger.getLogger(TaskTracker.class);
	@SuppressWarnings("rawtypes")
	private static Hashtable<String,Future> serviceTaskList= new Hashtable<String, Future>();
	
	
	public boolean checkTaskExits(String uniqueId){
		return serviceTaskList.containsKey(uniqueId);
	}
	public boolean removeTask(String uniqueId){
		serviceTaskList.remove(uniqueId);
		return (!checkTaskExits(uniqueId));
	}
	
	public String checkTaskStatus(String uniqueId){
		if(checkTaskExits(uniqueId)){
			if(serviceTaskList.get(uniqueId).isDone())
				return UftUtils.TASK_COMPLETE;
			else
				return UftUtils.TASK_RUNNING;
		}else{
			return UftUtils.TASK_NOT_EXISTS;
		}
	}
	public boolean addTask(String uniqueId,Future<Object> obj){
		if(!checkTaskExits(uniqueId)){
			serviceTaskList.put(uniqueId, obj);
			return true;
		}else{
			return false;
		}
	}
	public Object getOutput(String uniqueId){
		if(checkTaskStatus(uniqueId).equalsIgnoreCase(UftUtils.TASK_COMPLETE)){
			try {
				Future<Object> removed=serviceTaskList.remove(uniqueId);
				return (Object) removed.get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return e.getMessage();
				
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return e.getMessage();
			}
		}else{
			if(checkTaskStatus(uniqueId).equalsIgnoreCase(UftUtils.TASK_RUNNING)){
				return UftUtils.TASK_RUNNING;
			}else{
				return UftUtils.TASK_NOT_EXISTS;
			}
		}
	}
	

	@Scheduled(fixedDelayString="${wasService.task.cleaner.fixedDelay:120000}")
	private void serviceTaskCleaner(){
		logger.trace("Running wasServiceTaskClean....");
		Enumeration keys = serviceTaskList.keys();
		while(keys.hasMoreElements()){
			String id=(String) keys.nextElement();
			if(serviceTaskList.get(id).isDone()){
				logger.trace("Task Id: "+id+" is Done.. removing it...");
				serviceTaskList.remove(id);
			}
		}
	}
	
}
